package com.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * This program implements a multithreaded server that listens to port 8189 and
 * echoes back all client input.
 * 
 * @author Cay Horstmann
 * @version 1.20 2004-08-03
 */
public class ThreadedEchoServer {
	public static void main(final String[] args) {
		try {
			int i = 1;
			final ServerSocket s = new ServerSocket(8189);

			while (true) {
				final Socket incoming = s.accept();
				System.out.println("Spawning " + i);
				final Runnable r = new ThreadedEchoHandler(incoming);
				final Thread t = new Thread(r);
				t.start();
				i++;
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}
}

/**
 * This class handles the client input for one server socket connection.
 */
class ThreadedEchoHandler implements Runnable {
	/**
	 * Constructs a handler.
	 * 
	 * @param i
	 *            the incoming socket
	 * @param c
	 *            the counter for the handlers (used in prompts)
	 */
	public ThreadedEchoHandler(final Socket i) {
		incoming = i;
	}

	@Override
	public void run() {
		try {
			try {
				final InputStream inStream = incoming.getInputStream();
				final OutputStream outStream = incoming.getOutputStream();

				final Scanner in = new Scanner(inStream);
				final PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

				out.println("Hello! Enter BYE to exit.");

				// echo client input
				boolean done = false;
				while (!done && in.hasNextLine()) {
					final String line = in.nextLine();
					out.println("Echo: " + line);
					if (line.trim().equals("BYE")) {
						done = true;
					}
				}
			} finally {
				incoming.close();
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	private final Socket incoming;
}
